package com.zk.controller.UploadController;

import com.zk.entity.ResultDto;
import com.zk.utils.FTPUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;


/**
 * <p>
 *  文件图片上传
 * </p>
 *
 * @author jyx
 * @since 2020-12-18
 */
@Api(tags="上传照片")
@RestController
@RequestMapping(value = "/uploadFileServer")
public class NdeUploadFileServerController {

    @ApiOperation(value = "单文件上传到文件服务器")
    @PostMapping(value = "/uploadFolder")
    public ResultDto<String> uploadFolder(MultipartFile file) {
        try {

                String fileName = file.getOriginalFilename();

                //判断是否有文件且是否为图片文件
                if (fileName != null && !"".equalsIgnoreCase(fileName.trim()) && isImageFile(fileName)) {
                    //创建输出文件对象
                    byte[] bytes = file.getBytes();

                    String realName = UUID.randomUUID().toString()+ getFileType(fileName);

                    FTPUtil.sshSftp(bytes, realName);
                }

            return new ResultDto<>(200, "上传成功", "图片的名字");

        } catch (Exception e) {

            e.printStackTrace();

        }

        return new ResultDto<>(500, "上传失败");
    }

    @ApiOperation(value = "多文件上传到文件服务器")
    @PostMapping(value = "/uploadFolders")
    public ResultDto<String> uploadFolders(@RequestParam("files") MultipartFile[] files) {

        System.out.println("我进来了==================》》》");

        try {
            for (MultipartFile file : files)
            {
                uploadFolder(file);
            }
            return new ResultDto<>(200, "上传成功", "图片的名字");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResultDto<>(500, "上传失败");
    }

    private Boolean isImageFile(String fileName) {

        String[] img_type = new String[]{".jpg", ".jpeg", ".png", ".gif", ".bmp"};

        if (fileName == null) {

            return false;

        }
        fileName = fileName.toLowerCase();

        for (String type : img_type) {
            if (fileName.endsWith(type)) {
                return true;
            }
        }
        return false;
    }

    /**
     * <p>
     *  识别文件后缀
     * </p>
     *
     * @author jyx
     * @since 2020-12-18
     */
    private String getFileType(String fileName) {

        if (fileName != null && fileName.contains(".")) {

            return fileName.substring(fileName.lastIndexOf("."));

        }

        return "";


    }

}